import { useState, useEffect } from 'react'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { 
  UserIcon, 
  PencilIcon, 
  TrashIcon,
  EyeIcon,
  EyeSlashIcon,
  KeyIcon,
  PlusIcon,
  MagnifyingGlassIcon
} from '@heroicons/react/24/outline'
import { userApi, User } from '@/services/userApi'
import { toast } from 'react-hot-toast'

const userFormSchema = z.object({
  username: z.string().min(1, '用户名不能为空').max(50, '用户名最多50位字符'),
  nickname: z.string().max(50, '昵称最多50位字符').optional(),
  avatar: z.string().url('头像必须是有效的URL').optional().or(z.literal('')),
})

const passwordFormSchema = z.object({
  newPassword: z.string().min(6, '密码至少6位').max(50, '密码最多50位'),
})

type UserFormData = z.infer<typeof userFormSchema>
type PasswordFormData = z.infer<typeof passwordFormSchema>

const UserManagementPage = () => {
  const [users, setUsers] = useState<User[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [editingUser, setEditingUser] = useState<User | null>(null)
  const [showPasswordForm, setShowPasswordForm] = useState(false)
  const [showPasswords, setShowPasswords] = useState<Record<string, boolean>>({})

  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
    reset,
    setValue
  } = useForm<UserFormData>({
    resolver: zodResolver(userFormSchema)
  })

  const {
    register: registerPassword,
    handleSubmit: handleSubmitPassword,
    formState: { errors: passwordErrors, isSubmitting: isPasswordSubmitting },
    reset: resetPassword
  } = useForm<PasswordFormData>({
    resolver: zodResolver(passwordFormSchema)
  })

  // 加载用户列表
  const loadUsers = async () => {
    try {
      setLoading(true)
      const userList = await userApi.getAllUsers()
      setUsers(userList)
    } catch (error: any) {
      toast.error(error?.response?.data?.message || '加载用户列表失败')
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    loadUsers()
  }, [])

  // 搜索过滤
  const filteredUsers = users.filter(user => 
    user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
    (user.nickname && user.nickname.toLowerCase().includes(searchTerm.toLowerCase()))
  )

  // 编辑用户
  const handleEditUser = (user: User) => {
    setEditingUser(user)
    setValue('username', user.username)
    setValue('nickname', user.nickname || '')
    setValue('avatar', user.avatar || '')
    setShowPasswordForm(false)
  }

  // 保存用户信息
  const onSubmit = async (data: UserFormData) => {
    if (!editingUser) return

    try {
      await userApi.updateUser(editingUser.id, data)
      toast.success('用户信息更新成功')
      setEditingUser(null)
      reset()
      await loadUsers()
    } catch (error: any) {
      toast.error(error?.response?.data?.message || '更新用户信息失败')
    }
  }

  // 重置密码
  const onSubmitPassword = async (data: PasswordFormData) => {
    if (!editingUser) return

    try {
      await userApi.resetUserPassword(editingUser.id, data.newPassword)
      toast.success('密码重置成功')
      setShowPasswordForm(false)
      resetPassword()
    } catch (error: any) {
      toast.error(error?.response?.data?.message || '重置密码失败')
    }
  }

  // 删除用户
  const handleDeleteUser = async (user: User) => {
    if (!confirm(`确定要删除用户 "${user.username}" 吗？此操作不可撤销！`)) {
      return
    }

    try {
      await userApi.deleteUser(user.id)
      toast.success('用户删除成功')
      await loadUsers()
    } catch (error: any) {
      toast.error(error?.response?.data?.message || '删除用户失败')
    }
  }

  // 取消编辑
  const handleCancel = () => {
    setEditingUser(null)
    setShowPasswordForm(false)
    reset()
    resetPassword()
  }

  // 格式化日期
  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // 格式化最后在线时间
  const formatLastSeen = (lastSeen?: string) => {
    if (!lastSeen) return '从未在线'
    const now = new Date()
    const lastSeenDate = new Date(lastSeen)
    const diffInMinutes = Math.floor((now.getTime() - lastSeenDate.getTime()) / (1000 * 60))
    
    if (diffInMinutes < 1) return '刚刚'
    if (diffInMinutes < 60) return `${diffInMinutes}分钟前`
    if (diffInMinutes < 1440) return `${Math.floor(diffInMinutes / 60)}小时前`
    return `${Math.floor(diffInMinutes / 1440)}天前`
  }

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">👑 用户管理</h1>
          <p className="text-gray-600 mt-1">
            管理系统中的所有用户 👥
          </p>
        </div>
        <button
          onClick={loadUsers}
          className="btn-secondary flex items-center gap-2"
        >
          <MagnifyingGlassIcon className="h-5 w-5" />
          刷新列表
        </button>
      </div>

      {/* 搜索栏 */}
      <div className="card p-4">
        <div className="relative">
          <MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
          <input
            type="text"
            placeholder="搜索用户名或昵称..."
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
            className="input-field pl-10"
          />
        </div>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* 左侧：用户列表 */}
        <div className="lg:col-span-2">
          <div className="card">
            <div className="p-6 border-b border-gray-200">
              <h2 className="text-lg font-semibold text-gray-900">
                用户列表 ({filteredUsers.length})
              </h2>
            </div>
            
            {loading ? (
              <div className="p-8 text-center">
                <div className="loading-spinner w-8 h-8 mx-auto mb-4"></div>
                <p className="text-gray-600">加载中...</p>
              </div>
            ) : filteredUsers.length === 0 ? (
              <div className="p-8 text-center">
                <UserIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-600">没有找到用户</p>
              </div>
            ) : (
              <div className="divide-y divide-gray-200">
                {filteredUsers.map((user) => (
                  <div key={user.id} className="p-4 hover:bg-gray-50 transition-colors">
                    <div className="flex items-center justify-between">
                      <div className="flex items-center space-x-4">
                        {/* 头像 */}
                        <div className="w-12 h-12">
                          {user.avatar ? (
                            <img
                              src={user.avatar}
                              alt={user.nickname || user.username}
                              className="w-full h-full rounded-full object-cover"
                            />
                          ) : (
                            <div className="w-full h-full rounded-full bg-primary-500 flex items-center justify-center text-white text-lg font-bold">
                              {(user.nickname || user.username).charAt(0).toUpperCase()}
                            </div>
                          )}
                        </div>
                        
                        {/* 用户信息 */}
                        <div className="flex-1">
                          <div className="flex items-center gap-2">
                            <h3 className="font-semibold text-gray-900">
                              {user.nickname || user.username}
                            </h3>
                            <span className="text-sm text-gray-500">
                              @{user.username}
                            </span>
                            {user.isOnline && (
                              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
                                在线
                              </span>
                            )}
                            {user.partnerId && (
                              <span className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                已绑定
                              </span>
                            )}
                          </div>
                          <div className="text-sm text-gray-500 space-y-1">
                            <p>注册时间: {formatDate(user.createdAt)}</p>
                            <p>最后在线: {formatLastSeen(user.lastSeen)}</p>
                          </div>
                        </div>
                      </div>
                      
                      {/* 操作按钮 */}
                      <div className="flex items-center gap-2">
                        <button
                          onClick={() => handleEditUser(user)}
                          className="p-2 text-gray-400 hover:text-primary-600 transition-colors"
                          title="编辑用户"
                        >
                          <PencilIcon className="h-5 w-5" />
                        </button>
                        <button
                          onClick={() => handleDeleteUser(user)}
                          className="p-2 text-gray-400 hover:text-red-600 transition-colors"
                          title="删除用户"
                        >
                          <TrashIcon className="h-5 w-5" />
                        </button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>

        {/* 右侧：编辑表单 */}
        <div className="lg:col-span-1">
          {editingUser ? (
            <div className="card p-6">
              <div className="flex items-center justify-between mb-6">
                <h3 className="text-lg font-semibold text-gray-900">
                  编辑用户: {editingUser.username}
                </h3>
                <button
                  onClick={handleCancel}
                  className="text-gray-400 hover:text-gray-600"
                >
                  ✕
                </button>
              </div>

              {!showPasswordForm ? (
                <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
                  {/* 用户名 */}
                  <div>
                    <label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-2">
                      用户名
                    </label>
                    <input
                      {...register('username')}
                      type="text"
                      id="username"
                      className={`input-field ${errors.username ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                    />
                    {errors.username && (
                      <p className="mt-1 text-sm text-red-600">{errors.username.message}</p>
                    )}
                  </div>

                  {/* 昵称 */}
                  <div>
                    <label htmlFor="nickname" className="block text-sm font-medium text-gray-700 mb-2">
                      昵称
                    </label>
                    <input
                      {...register('nickname')}
                      type="text"
                      id="nickname"
                      className={`input-field ${errors.nickname ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                      placeholder="可选"
                    />
                    {errors.nickname && (
                      <p className="mt-1 text-sm text-red-600">{errors.nickname.message}</p>
                    )}
                  </div>

                  {/* 头像 */}
                  <div>
                    <label htmlFor="avatar" className="block text-sm font-medium text-gray-700 mb-2">
                      头像URL
                    </label>
                    <input
                      {...register('avatar')}
                      type="url"
                      id="avatar"
                      className={`input-field ${errors.avatar ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                      placeholder="https://example.com/avatar.jpg"
                    />
                    {errors.avatar && (
                      <p className="mt-1 text-sm text-red-600">{errors.avatar.message}</p>
                    )}
                  </div>

                  {/* 按钮组 */}
                  <div className="space-y-3">
                    <button
                      type="submit"
                      disabled={isSubmitting}
                      className="btn-primary w-full"
                    >
                      {isSubmitting ? '保存中...' : '保存更改'}
                    </button>
                    
                    <button
                      type="button"
                      onClick={() => setShowPasswordForm(true)}
                      className="btn-secondary w-full flex items-center justify-center gap-2"
                    >
                      <KeyIcon className="h-4 w-4" />
                      重置密码
                    </button>
                  </div>
                </form>
              ) : (
                <form onSubmit={handleSubmitPassword(onSubmitPassword)} className="space-y-4">
                  <div className="text-center mb-4">
                    <KeyIcon className="h-8 w-8 text-gray-400 mx-auto mb-2" />
                    <p className="text-sm text-gray-600">
                      为 <strong>{editingUser.username}</strong> 重置密码
                    </p>
                  </div>

                  {/* 新密码 */}
                  <div>
                    <label htmlFor="newPassword" className="block text-sm font-medium text-gray-700 mb-2">
                      新密码
                    </label>
                    <input
                      {...registerPassword('newPassword')}
                      type="password"
                      id="newPassword"
                      className={`input-field ${passwordErrors.newPassword ? 'border-red-300 focus:border-red-500 focus:ring-red-500' : ''}`}
                      placeholder="至少6位字符"
                    />
                    {passwordErrors.newPassword && (
                      <p className="mt-1 text-sm text-red-600">{passwordErrors.newPassword.message}</p>
                    )}
                  </div>

                  {/* 按钮组 */}
                  <div className="space-y-3">
                    <button
                      type="submit"
                      disabled={isPasswordSubmitting}
                      className="btn-primary w-full"
                    >
                      {isPasswordSubmitting ? '重置中...' : '重置密码'}
                    </button>
                    
                    <button
                      type="button"
                      onClick={() => setShowPasswordForm(false)}
                      className="btn-secondary w-full"
                    >
                      返回编辑
                    </button>
                  </div>
                </form>
              )}
            </div>
          ) : (
            <div className="card p-6 text-center">
              <UserIcon className="h-12 w-12 text-gray-400 mx-auto mb-4" />
              <p className="text-gray-600">选择一个用户进行编辑</p>
            </div>
          )}
        </div>
      </div>
    </div>
  )
}

export default UserManagementPage
